
var SCROLL_ANIMATE_TIMING = 4000;
var CHECK_HASH_TIMING = 300;

function init() {

    $.ajax({
        url: "readPortfolio.php",
        dataType: "json",
        success:function(data, textStatus, jqXHR) {
//            alert("on success");
            portfolio.config = data;
            portfolio.init();
        }
    });

}


var portfolio={

    config: null, // reference to portfolio configuration
    allItems: [], // all items enumerated
    icon_section_container: null, // reference to element containing all icon section

    mainIconPageShown: false,
    mainIconPageInitiated: false,



    init: function () {
        hashAddress.init();
        $(window).scroll(onWindowScroll);
        this.icon_section_container = $("#icon_section_container");

        this.addItemsToList();
        this.decideOnHash();
        toggleSaturnVisibility();
    },

    addItemsToList : function () {
        for (var i = 0; i < this.config.sections.length; i++) {
            var section = this.config.sections[i];
            for (var j = 0; j < section.items.length; j++) {
                section.items[j].listIndex = this.allItems.length;
                this.allItems.push(section.items[j]); // adding to the full array
            }
        }
    },

    decideOnHash: function() {
        // if there is an hash in the address, it opens the item
        if (!isStringEmpty(window.location.hash) && window.location.hash.search("itemId") > 0) {
            var arr = window.location.hash.split("=");
            this.showItemDetail(this.allItems[arr[1]]);
        } else {
            this.showIconPage();
        }
    },

    showIconPage: function () {

        if (!this.mainIconPageInitiated) {
            for (var i = 0; i < this.config.sections.length; i++) {
                var section = this.config.sections[i];
                this.populateSection(section);
            }
            this.mainIconPageInitiated = true;
        }

        if (!this.mainIconPageShown) {
            window.location.hash = "";
            hashAddress.sinc();

            if ("main_content" != this.icon_section_container.parent().attr("id")) {
                this.icon_section_container.detach();

                // if it not shown, then show it
                var mainContent = $("#main_content");
                mainContent.empty();
                mainContent.append(this.icon_section_container);
            }
            this.mainIconPageShown = true;
        }


    },

    populateSection: function (section) {
        var sectionName = section.name;
        var sectionContent = $("#" + sectionName + "_section .section_content");
        
        if (sectionContent.length < 1) return;

        for (var i=0; i < section.items.length; i++) {
            this.addItem(sectionContent, section.items[i]);
        }
    },

    addItem: function (sectionContent, itemData) {
        var width;
        if (isSet(itemData, "iconHorSize")) {
            width = itemData.iconHorSize * this.config.itemWidthStep;
        } else {
            width = this.config.itemWidthStep;
        }

        var height;
        if (isSet(itemData, "iconVertSize")) {
            height = itemData.iconVertSize * this.config.itemHeightStep;    
        } else {
            height = this.config.itemHeightStep;
        }





        var iconBlock = $("<div/>", {"class": "icon_block"}).css({
            "height": height,
            "width" : width,
            "background-image": "url("+ itemData.iconPath +")"
        });


        var infoBlock = $("<div/>", {"class": "info_block"}).css({
            "height": height,
            "width" : width
        });

        var infoWrapper = $("<div class='info_wrapper'/>").append($("<div class='title'>"+ itemData.title +"</div>"));
        if (isSet(itemData, "url")) {
            var linkStr = '<div class="link"><a href="http://' + itemData.url + '" style="color:'+getColorValue(itemData.fontColor)+';">'+itemData.url+'</a></div>';
            infoWrapper.append($(linkStr));
        }

        if (itemData.description != null)
            infoWrapper.append($('<div class="description">' + itemData.description + '</div>'));


        infoBlock.append(infoWrapper);
        infoBlock.append(infoWrapper);


        var itemElement = $("<a href='#itemId="+ itemData.listIndex +"' class='item'/>").css({
            "height": height,
            "width" : width,
            "color" : getColorValue(itemData.fontColor),
            "backgroundColor": getColorValue(itemData.backgroundColor)
        } );

        // put the reference to have it handy in on_click method
        itemElement.data("itemData", itemData);



        if (isTrue(itemData.iconShowedDefault)) {

            itemElement.data("iconShowedDefault", true);
        } else {
            iconBlock.css("opacity", 0);
            itemElement.data("iconShowedDefault", false);
        }

        itemElement.append(iconBlock);
        itemElement.append(infoBlock);
        itemElement.append($("<div class='item_section_tag'>"+ itemData.sectionName +"</div>"));


        itemElement.hover(onItemMouseOver, onItemMouseOut);
        itemElement.click(onIconClick);

        sectionContent.append(itemElement);

    /* <div class="item" style="width: 400px; height: 200px; background: #d9ceaf; color: #161616;">
            <div class="icon_block" style="background: url(content/01_web/01_enertrac_video/icon.png); width: 400px; height: 200px;"></div>
            <div class="info_block" style="width: 400px; height: 200px;">
                <div class="info_wrapper">
                    <div class="title">NuEnergen</div>
                    <div class="link"><a href="http://www.nuenergen.com" style="color:#161616;">www.nuenergen.com</a></div>
                    <div class="description">Design and implementation informational portal for dear to heart energy consulting company.</div>
                </div>
                <div class="item_section_tag">WEB</div>
            </div>
        </div>*/


    },

    showSection: function(sectionId) {
        this.showIconPage();
        this.scrollToSection(sectionId);
    },

    scrollToSection: function (sectionId) {
        var section = $(sectionId);
        if (section.length != 1) return;   // no such id
        $('html, body').stop();

        var newScrollTop = section.offset().top - $("#main_header").outerHeight() + 1;
//        alert("Current: " + $("html").scrollTop() + " | new: " + newScrollTop);
        $('html, body').animate({scrollTop: newScrollTop}, SCROLL_ANIMATE_TIMING, "easeOutQuart") ;
    },



    showItemDetail: function (itemData) {

        var headerBlock = $("<div class='item_detail_title' />")
                .append($("<h1> <span class='red_title'>" + itemData.sectionName + "</span>: " + itemData.title + "</h1>"))
                .append($('<div class="red_divider"></div>'));


        var itemDetailContent = $('<div class="item_detail_content" />');

        if (itemData.description != null)
            itemDetailContent.append($('<div class="item_detail_description">' + itemData.description + '</div>'));

        if (itemData.url != null)
            itemDetailContent.append($('<div class="details_url"><a href="http://' + itemData.url + '">' + itemData.url + '</a></div>'));

        itemDetailContent.append($('<div class="padding_b20"></div>'));

        if (itemData.details != null)
            itemDetailContent.append($('<div class="item_detail_info">' + itemData.details + '</div>'));
//            itemDetailContent.append($('<div class="item_detail_info"><div class="red_marker"></div>' + itemData.details + '</div>'));

        // adding tags
        var tagWrapper = $('<div class="item_detail_tag_wrapper" />');
        for (var i = 0; i < itemData.tags.length; i++) {
            tagWrapper.append($('<div class="item_detail_tag">' + itemData.tags[i] + '</div>'));
        }

        itemDetailContent.append(tagWrapper);

        var imageHolder = $('<div class="item_detail_image_holder" />');

        if (itemData.customHtml != null) {
            // if type is customHtml is not empty, then we load only that html
            var customHtml = $(itemData.customHtml);
            imageHolder.append(customHtml);

        } else {
            // otherwise load images

            for (var i = 0; i < itemData.images.length; i++) {
                var div = $('<div class="item_detail_image_wrapper" />');
                var image = $('<img src="' + itemData.images[i] + '" class="item_detail_image" alt="" />');
                div.append(image);
                if (i < itemData.images.length - 1) {
                    div.append($('<div class="item_detail_image_divider" />'));
                }
                imageHolder.append(div);

                // for the last image add load handler to preload items around
                if (i == itemData.images.length -1) {
                    image.ready(function() {
                        portfolio.preloadAround(itemData.listIndex);
                    });
                }
            }
        }

        var prevButton = $('<a class="item_detail_prev" href="#itemId=' + (itemData.listIndex - 1) + '" />');
        var nextButton = $('<a class="item_detail_next" href="#itemId=' + (itemData.listIndex + 1) + '" />');
        if (itemData.listIndex == 0) {
            prevButton.hide();
        } else {
            prevButton.data("itemData", this.allItems[itemData.listIndex - 1 ]);
            prevButton.click(goToItemDetail);
        }
        if (itemData.listIndex == this.allItems.length - 1) {
            nextButton.hide();
        } else {
            nextButton.data("itemData", this.allItems[itemData.listIndex + 1 ]);
            nextButton.click(goToItemDetail);

            // adding moving forward on image holder click
            imageHolder.data("itemData", this.allItems[itemData.listIndex + 1 ]);
            imageHolder.click(goToItemDetail);
        }

        var detailPanel = $('<div class="item_detail_panel" />');
        detailPanel.append(prevButton);
        detailPanel.append(imageHolder);
        detailPanel.append(nextButton);

        itemDetailContent.append(detailPanel);

        var itemDetailWrapper = $("<div class='item_detail_wrapper' />");
        itemDetailWrapper.append(headerBlock);
        itemDetailWrapper.append(itemDetailContent);


        var mainContent = $("#main_content");

        if (this.mainIconPageShown) {
            $("#icon_section_container").detach();
            this.mainIconPageShown = false;
        }

        mainContent.empty();
        mainContent.append(itemDetailWrapper);

        //        $('html, body').animate({scrollTop: 0}, SCROLL_ANIMATE_TIMING, "easeOutQuart");


        
    },

    preloadAround:function (index) {
        // preload images around current item
        var depth = 1;
        var image = new Image();
        for (var i = index -1; i >=0 && i >= index - depth; i--) {
            var item = this.allItems[i];
//            dumpSource("preloading: " + i);
            for (var j = 0; j < depth; j++ ) {
                image.src = item.images[j];
            }
        }

        for (var i = index + 1; i < this.allItems.length && i <= index + depth; i++) {
            var item = this.allItems[i];
//            dumpSource("preloading: " + i);
            for (var j = 0; j < depth; j++ ) {
                image.src = item.images[j];
            }
        }

    }


}


function goToItemDetail(event) {
    event.preventDefault();
    var item = $(this).data("itemData");
    window.location.hash = "itemId=" + item.listIndex;
    hashAddress.sinc(); // to prevent from triggering again
    portfolio.showItemDetail(item);
}

function dumpSource(obj) {
    var div = $("<div/>");
    if (obj == null) {
        div.text("NULL");
    } else
        div.text(obj.toSource());

    $("#testSection").append(div)
}

function onIconClick(event) {
    event.preventDefault();
    window.location.hash = this.hash;
    hashAddress.sinc();
    portfolio.showItemDetail($(this).data("itemData"));
}

function onItemMouseOver(event) {
    if ($(this).data("iconShowedDefault")) {
        fadeOutItemPicture($(this));
    } else {
        fadeInItemPicture($(this));
    }
}

function onItemMouseOut(event) {
    if ($(this).data("iconShowedDefault")) {
        fadeInItemPicture($(this));

    } else {
        fadeOutItemPicture($(this));
    }
}

function fadeOutItemPicture(itemBlock) {
    $('.icon_block', itemBlock).stop().fadeTo("slow", 0, "easeOutCubic");
}

function fadeInItemPicture(itemBlock) {
    $('.icon_block', itemBlock).stop().fadeTo("slow", 1, "easeOutCubic");
}

function onWindowScroll(event) {
    toggleSaturnVisibility();

}

function toggleSaturnVisibility() {
    if ($(window).scrollTop() > 50) {
        $(".saturn").css("opacity", 0);
    } else {
        $(".saturn").css("opacity", 1);
    }
}

/** Returns true if property is set. */
function isSet(obj, propName) {
    if (obj.hasOwnProperty(propName) && obj[propName] != null) {
        if (typeof obj[propName] == 'string' || obj[propName] instanceof String) {
            return obj[propName].length > 0;
        }
        return true;
    }
    return false;
}

/** Checks if property indicates positive regardless of the type used. */
function isTrue(value) {
    if (value == null || value == undefined) return false;

    if (typeof value == 'string' || value instanceof String) {
        value = value.toLowerCase();
        return "true" == value || "yes" == value;
    } else if (typeof value == 'number' || value instanceof Number) {
        return value != 0;
    } else if (typeof value == 'boolean' || value instanceof Boolean) {
        return value == true;
    }

    return false;
}

function isStringEmpty(str) {
    return str == null || str.length == 0;
}

function strEquals(s1, s2) {
    if (isStringEmpty(s1) && isStringEmpty(s2)) return true;

    return s1 == s2;
}

function getColorValue(property) {
    if (isStringEmpty(property)) return null;

    if ("#" == property.charAt(0)) {
        return property;
    }
    return "#" + property;

}

function hasHtml5() {
    return !!document.createElement('canvas').getContext;
}

/** Small class to handle hash changes. */
var hashAddress = {
    currentHash: null,

    init:function() {
        this.sinc();
        setTimeout('hashAddress.checkHash()', CHECK_HASH_TIMING);
    },

    checkHash: function() {
        var newHash = window.location.hash;
        if (!strEquals(newHash, this.currentHash)) {
            portfolio.decideOnHash();
            this.currentHash = newHash;
        }
        setTimeout('hashAddress.checkHash()', CHECK_HASH_TIMING);
    },

    sinc: function() {
        this.currentHash = window.location.hash;
    }


}